import {
  addChannelService,
  delChannelService,
  editChannelService,
  getChannelsService,
  getArticlesService,
  delArticleService,
  addArticleService,
  getArticleInfoService,
  updateArticleInfoService,
} from "@/api/article";
import { ElMessage, ElMessageBox } from "element-plus";
import { defineStore, storeToRefs } from "pinia";
import { ref } from "vue";
import axios from "axios";

//不需要持久化数据的维护仓库
export const useNoPersistStore = defineStore("noPersist", () => {
  const drawerVisible = ref(false);
  const header = ref("");
  const loading = ref(false);
  //文章编辑和添加的抽屉组件数据
  const drawerForm = ref({
    id: "",
    title: "",
    cate_id: "",
    content: "",
    cover_img: "",
    state: "",
  });
  const imgUrl = ref("");
  //文章详情展示相关
  const articleInfoVisible = ref(false);
  const articleInfo = ref({
    title: "",
    nickname: "",
    pub_data: "",
    cover_img: "",
    cate_name: "",
    content: "",
  });
  return {
    drawerVisible,
    articleInfoVisible,
    drawerForm,
    imgUrl,
    articleInfo,
    header,
    loading,
  };
});

export const useChannelStore = defineStore(
  "channel",
  () => {
    //存储文章分类的列表
    const channelList = ref([]);
    //控制对话框的显示隐藏
    const dialogVisible = ref(false);

    //对话框表单信息
    const dialogForm = ref({
      id: "",
      cate_name: "",
      cate_alias: "",
    });
    const form = ref();
    //对话框标题
    const title = ref("");
    //添加文章分类表单的校验
    const rules = {
      cate_name: [
        { required: true, message: "请输入分类名称", trigger: "blur" },
        {
          pattern: /^\S{1,10}$/,
          message: "分类名称必须是1-10位的非空字符",
          trigger: "blur",
        },
      ],
      cate_alias: [
        { required: true, message: "请输入分类别名", trigger: "blur" },
        {
          pattern: /^[0-9a-zA-Z]{1,15}$/,
          message: "分类别名必须是1-15位的大小写字母和数字",
          trigger: "blur",
        },
      ],
    };

    //获取文章分类
    const getChannels = async () => {
      const res = await getChannelsService();
      channelList.value = res.data;
    };
    //文章分类删除
    const handleDelete = (row) => {
      ElMessageBox.confirm("你确定要删除这条文章分类吗?", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(async () => {
          const res = await delChannelService(row.id);
          ElMessage.success(res.message);
          getChannels();
        })
        .catch(() => {
          ElMessage({
            type: "success",
            message: "取消删除",
          });
        });
    };

    //文章分类编辑
    const handleEdit = async (row) => {
      dialogVisible.value = true;
      dialogForm.value = { ...row };
      title.value = "编辑文章";
    };

    //添加文章分类
    const addChannel = async () => {
      dialogVisible.value = true;
      dialogForm.value = {
        id: "",
        cate_name: "",
        cate_alias: "",
      };
      title.value = "添加分类";
    };
    //对话框表单的提交
    const submit = async (dialogForm) => {
      await form.value.validate();
      if (dialogForm.id) {
        const res = await editChannelService(dialogForm);
        dialogVisible.value = false;
        ElMessage.success(res.message);
        getChannels();
      } else {
        const res = await addChannelService(dialogForm);
        dialogVisible.value = false;
        ElMessage.success(res.message);
        getChannels();
      }
    };

    //关闭弹窗
    const close = () => {
      dialogVisible.value = false;
    };
    return {
      channelList,
      dialogVisible,
      dialogForm,
      title,
      rules,
      form,
      getChannels,
      handleEdit,
      handleDelete,
      addChannel,
      close,
      submit,
    };
  },
  { persist: true }
);

export const useArticleStore = defineStore(
  "article",
  () => {
    const noPersistStore = useNoPersistStore();
    const {
      drawerVisible,
      drawerForm,
      imgUrl,
      articleInfoVisible,
      articleInfo,
      header,
      loading,
    } = storeToRefs(noPersistStore);

    //文章查询表单数据
    const queryForm = ref({
      pagenum: 1,
      pagesize: 5,
      cate_id: null,
      state: null,
    });
    //文章数据
    const articleList = ref([]);
    //文章总条数
    const total = ref(0);
    //获取文章数据
    const getArticles = async () => {
      loading.value = true;
      const res = await getArticlesService(queryForm.value);
      articleList.value = res.data;
      total.value = res.total;
      loading.value = false;
    };
    //文章条件搜索
    const search = () => {
      getArticles();
    };
    const reset = () => {
      queryForm.value.cate_id = "";
      queryForm.value.state = "";
      getArticles();
    };
    const handleCurrentChange = (num) => {
      console.log(num);
      queryForm.value.pagenum = num;
      getArticles();
    };
    const handleSizeChange = (num) => {
      queryForm.pagesize = num;
      getArticles();
    };

    //文章删除
    const handleDelete = (row) => {
      ElMessageBox.confirm("你确定要删除这篇文章吗?", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          //发送删除请求
          await delArticleService(row.id);
          ElMessage.success("文章删除成功");
          getArticles();
        })
        .catch(() => {
          ElMessage.success("取消删除成功");
        });
    };

    //------------------------------------------------------------------
    const form = ref();
    const editorRef = ref();
    //添加图片
    const uploadImg = (uploadFile) => {
      drawerForm.value.cover_img = uploadFile.raw;
      //临时创建了一个图像显示的地址
      imgUrl.value = URL.createObjectURL(uploadFile.raw);
    };
    //抽屉表单的校验规则
    const rules = {
      title: [
        {
          required: true,
          message: "请输入文章标题",
          trigger: "blur",
        },
        {
          min: 1,
          max: 30,
          message: "文章长度必须要1-30位的任意字符",
          trigger: "blur",
        },
      ],
      cate_id: [
        {
          required: true,
          message: "请选择文章分类",
          trigger: "blur",
        },
      ],
      content: [
        {
          required: true,
          message: "请输入文章内容",
          trigger: "blur",
        },
      ],
      cover_img: [
        {
          required: true,
          message: "请添加文章封面",
          trigger: "blur",
        },
      ],
    };
    //文章添加
    const addArticle = () => {
      header.value = "添加文章";
      drawerVisible.value = true;
    };
    //文章编辑
    const handleEdit = async (row) => {
      header.value = "编辑文章";
      const res = await getArticleInfoService(row.id);
      drawerForm.value = res.data;
      //图片单独回显，这里不需要创建临时的地址
      imgUrl.value =
        "http://big-event-vue-api-t.itheima.net" + drawerForm.value.cover_img;

      drawerVisible.value = true;

      //数据提交
      //需要将网络图片地址转化成file对象
      const file = await imageUrlToFile(imgUrl.value);
      drawerForm.value.cover_img = file;
    };

    // 函数将网络图片地址转换为File对象
    const imageUrlToFile = async (imageUrl) => {
      try {
        // 使用axios获取网络图片的二进制数据
        const response = await axios.get(imageUrl, {
          responseType: "arraybuffer",
        });

        // 将二进制数据转换为Blob对象
        const blob = new Blob([response.data]);

        // 创建File对象，参数包括Blob对象和文件名
        const file = new File([blob], "image.jpg", { type: "image/jpeg" });

        return file;
      } catch (error) {
        console.error("Error converting image URL to file:", error);
        throw error;
      }
    };
    //----------------------------------------------------------------------------------
    //文章发布
    const publish = async (state) => {
      if (drawerForm.value.id) {
        drawerForm.value.state = state;
        const fd = new FormData();
        for (let i in drawerForm.value) {
          fd.append(i, drawerForm.value[i]);
        }
        const res = await updateArticleInfoService(fd);
        ElMessage.success(res.message);
      } else {
        await form.value.validate();
        drawerForm.value.state = state;
        const fd = new FormData(); //创建formData对象
        for (let i in drawerForm.value) {
          fd.append(i, drawerForm.value[i]);
        }
        const res = await addArticleService(fd);
        ElMessage.success(res.message);
        //直接可以看到相关文章列表
        const num = total.value + 1;
        //Math.ceil向上取整
        queryForm.value.pagenum = Math.ceil(num / queryForm.value.pagesize);
      }
      getArticles();
      drawerForm.value = {
        id: "",
        title: "",
        cate_id: "",
        content: "",
        state: "",
      };
      imgUrl.value = "";
      editorRef.value.setHTML("");
      drawerVisible.value = false;
    };
    //文章预览
    const viewArticle = async (id) => {
      const res = await getArticleInfoService(id);
      //根据返回的数据做文章详情的回显
      articleInfo.value = res.data;

      articleInfo.value.cover_img =
        "http://big-event-vue-api-t.itheima.net" + res.data.cover_img;
      articleInfoVisible.value = true;
    };
    return {
      queryForm,
      articleList,
      total,
      form,
      rules,
      editorRef,
      addArticle,
      getArticles,
      search,
      reset,
      handleDelete,
      handleEdit,
      handleCurrentChange,
      handleSizeChange,
      uploadImg,
      publish,
      viewArticle,
    };
  },
  {
    persist: true,
  }
);
